param ([string]$global_mode)

function RenameSubsIdxSub() {
    $movies = Get-ChildItem $PSScriptRoot | where {! $_.PSIsContainer}
    ForEach ($movie in $movies) {
        if ($movie -match "(.*\.)s(\d{2})e(\d{2})(.*)\.(avi|mkv|mp4)$") {
            $s = $matches[2]
            $e = $matches[3]
            $se_ident = "S" + $s + "E" + $e
            $is_ident = if ($global_mode -eq "SEE") {$s.substring(1) + $e} else {$se_ident}
            $movie_basename = $matches[1] + $se_ident + $matches[4]
            $subfiles = Get-ChildItem $PSScriptRoot | where {! $_.PSIsContainer}
            ForEach ($subfile in $subfiles) {
                if ($subfile -match ("(.*[_.]" + $is_ident + ".*)\.(idx|sub)$")) {
                    $basename = $matches[1]
                    $idxpath = Join-Path $PSScriptRoot ($basename + ".idx")
                    $subpath = Join-Path $PSScriptRoot ($basename + ".sub")
                    if ((Test-Path $idxpath) -and (Test-Path $subpath)) {
                        Rename-Item -Path $idxpath -NewName ($movie_basename + ".idx")
                        Rename-Item -Path $subpath -NewName ($movie_basename + ".sub")
                        Write-Host "    Fixed idx/sub file names for '" -nonewline; Write-Host "$movie_basename" -f green -nonewline
                        Write-Host "'."
                    }
                }
            }
        }
    }
}

RenameSubsIdxSub



